<?php

namespace App\Services\Core\Sms\Chuanglan;

use App\Helpers\Logger\SLogger;
use App\Models\Factory\CacheFactory;
use App\Services\Core\Sms\SmsService;
use App\Helpers\Http\HttpClient;
use App\Models\Orm\MessageLog;
use Log;

/**
 * 创蓝短信通道
 * Class ChuanglanService
 * @package App\Services\Core\Sms\Chuanglan
 */
class ChuanglanService extends SmsService
{

    /**
     * 请求创蓝发送短信
     */
    //创蓝发送短信接口URL, 如无必要，该参数可不用修改
    const API_SEND_URL = 'http://sms.253.com/msg/send';

    //创蓝短信余额查询接口URL, 如无必要，该参数可不用修改
    const API_BALANCE_QUERY_URL = 'http://sms.253.com/msg/balance';

    const API_ACCOUNT = 'N13811875123';

    const API_PASSWORD = '612941';

    /**
     * @param $mobile
     * @return string
     */
    public static function send($mobile)
    {
        $code = rand(1000, 9999);
        $msg = "【现金贷】（安稳贷）您好，您的验证码是" . $code;
        $needstatus = 1;
        if (preg_match('/^0?(13|14|15|17|18)[0-9]{9}$/', $mobile)) {
            // 将该验证码和手机号发送给第三方，第三方通过短信的方式向用户发送信息
            //创蓝接口参数
            $postArr = array(
                'un' => self::API_ACCOUNT,
                'pw' => self::API_PASSWORD,
                'msg' => $msg,
                'phone' => $mobile,
                'rd' => $needstatus,
            );
            self::curlPost(self::API_SEND_URL, $postArr);
            SLogger::getStream()->info('这是创蓝短信通道!');
            CacheFactory::putValueToCache($mobile . '_code', $code, 5 * 60);
            CacheFactory::putValueToCache($mobile . '_send_limit', $mobile, 60);

            return json_encode(array('isSuccess' => "1", 'status' => "1", "msg" => "短信验证码发送成功", "check" => $code));
        } else {
            return json_encode(array('isSuccess' => "0", 'status' => "0", "error" => "44000227", "msg" => "短信验证码发送失败"));
            // 手机号格式不正确
        }
    }


    private static function curlPost($url, $postFields)
    {
        $postFields = http_build_query($postFields);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}
